/*!
 * szim v1.0.0 (盛筑即时通讯)
 * author：sudukai@qq.com
 * date: 2023-02-20创1.0.0, 03-08 重构1.1.0
 */
layui.define(['layer', 'laytpl', 'element', 'imtree', 'form', 'dropdown'], function (exports) {
  var $ = layui.$, layer = layui.layer, laytpl = layui.laytpl, element = layui.element, imtree = layui.imtree, form = layui.form, dropdown = layui.dropdown, stope = layui.stope;
  var version = "1.1.0",
    cache = {//置内存里
      mine: {},   //当前用户
      chat: [],   //聊天历史记录
      friend: [], //部门及人员
      group: [],  //群
      base: {},    //配置
      badgeCount: 0 //当前badge总数，用于缩小时提示
    },
    current = {//当前面板
      isShowLog: false,  //是否打开聊天记录
      chatObj: {},       //当前对象
      chatType: 1,       //当前聊天类型(1=单聊，2=群聊，3=系统消息)
      chatData: [],       //当前面板聊天记录，max:20条，每切换时更改--渲染用
      chathis: [],       //当前聊天历史记录
      intree: {},
      page: 1,
      limit: 20
    },
    flow = {//流程消息
      ids: [],
      list: []
    },
    sysmsg = {//系统消息
      ids: [],
      list: []
    },
    elemimbox = '#imchatbox',
    minbox = {
      btn: '.szim-minbtn',
      badge: '#szim-min-badge'
    },
    hidecss = 'layui-hide',
    szwin = { //窗体使用的
      old_x: 0,
      old_y: 0,
      is_max: false,
      move: false,
      _x: 0,
      _y: 0,
      maxW: $(window).width(),
      maxH: $(window).height(),
      winX: 0,
      winY: 0
    };

  //主窗体模板
  var mainTpl = ['<div class="im-chat-box" id="imchatbox">'
    , '<div class="chat-row" id="chatrowbox">'
    , '  <div class="chat-col-1">'
    , '    <div class="win-head1 tf-head"></div>'
    , '    <ul class="chat-tools">{{- d.btns }}</ul>'
    , '    <ul class="chat-set">{{- d.set }}</ul>'
    , '  </div>'
    , '  <div class="chat-col-2">'
    , '    <div class="win-head2 tf-head"></div>'
    , '    <div class="kg-row chat-c-t">{{- d.search }}</div>'
    , '    <div class="kg-list">{{- d.list }}</div>'
    , '    <div class="kg-dept">'
    , '        <div class="kg-bt">群聊</div>'
    , '        <div class="kg-group">{{- d.group }}</div>'
    , '        <div class="kg-bt">部门</div>'
    , '        <div class="kg-deptuser"></div>'
    , '    </div>'
    , '  </div>'
    , '  <div class="chat-col-3 bg-sz">'
    , '    <div class="kg-user-title"></div>'
    , '    <div class="win-head tf-head"></div>'
    , '    <div class="kg-row win-btns">'
    , '      <a href="javascript:;" class="kg-col win-min" szim-event="winmin" ></a>'
    , '      <a href="javascript:;" class="kg-col win-max" szim-event="winmax"></a>'
    , '      <a href="javascript:;" class="kg-col win-restore" szim-event="winrestore"></a>'
    , '      <a href="javascript:;" class="kg-col win-close" szim-event="winclose"></a>'
    , '    </div>'
    , '    <div class="kg-content">{{- d.content }}</div>'
    , '  </div>'
    , '</div>'
    , '</div>'
    , '<div class="szim-minbtn" szim-event="szimminbtn">' //缩小后
    , '  <span class="layui-badge szim-min-badge layui-hide" id="szim-min-badge">0</span>'
    , '  <img src="{{ d.avatar }}" alt=""/>'
    , '  <span>{{ d.minTitle }}</span>'
    , '</div>'].join(''),

    //按钮组
    btnTpl = ['<li><a href="javascript:;"><img class="chat-avatar" src="{{ d.avatar }}" alt="头像" /></a></li>'
      , '<li><a href="javascript:;" szim-event="cutchatmessage"><i class="layui-icon layui-icon-dialogue"></i></a></li>'
      , '<li><a href="javascript:;" szim-event="cutchatuserlist"><i class="layui-icon layui-icon-username"></i></a></li>'
    ].join(''),
    //设置
    setTpl = ['<li><a href="javascript:;" szim-event="hlight"><i class="layui-icon layui-icon-light"></i></a></li>'
      , '<li><a href="javascript:;" szim-event="about"><i class="layui-icon layui-icon-about"></i></a></li>'
    ].join(''),
    //搜索
    searchTpl = ['<div class="kg-col keywords-box"><input type="text" name="keywords" placeholder="搜索" autocomplete="off" /></div>'
      , '<div class="kg-col"><button type="button" class="chat-btn-search"><i class="layui-icon layui-icon-search"></i></button></div>'
    ].join(''),
    //聊天内容盒子
    contentTpl = ['<div class="sz-chatbox"></div>'
      , '<div class="sz-chattools">'
      , '  <span class="layui-icon layui-icon-face-smile-b c-one" title="选择表情" szim-event="face"></span>'
      , '  <span class="layui-icon layui-icon-picture" title="上传图片" szim-event="image"></span>'
      , '  <span class="layui-icon layui-icon-export" title="发送文件" szim-event="image" data-type="file"></span>'
      , '  <span class="layui-icon layui-icon-video" title="发送网络视频" szim-event="media" data-type="video"></span>'
      , '  <span class="layui-icon layui-icon-website" title="超链接" szim-event="website"></span>'
      , '  <span class="layui-icon layui-icon-time c-right" title="聊天记录" szim-event="chatLog"></span>'
      , '</div>'
      , '<div class="sz-chatinput">'
      , '  <div class="sz-chat-input">'
      , '      <textarea class="chatinput"></textarea></div>'
      , '   </div>'
      , '  <div class="sz-chat-send">'
      , '    <span class="szim-send-btn" szim-event="doSend" title="Ctrl+Enter">发送</span>'
      , '  </div>'
      , '</div>'
    ].join(''),
    //流程内容盒子
    flowTpl = ['<div class="sz-flowbox"></div>'].join(''),
    //流程内容
    flowrowTpl = ['<div class="flow-row {{ d.status ==1 ? " " : " ithis " }}" szim-event="flowRow" id="flow_msg_{{ d.id }}" data-id="{{ d.id }}" data-url="{{ d.m_url }}">'
      , '  <div class="fl-left"><span class="flow-badge">{{ d.modu_name || "" }}</span></div>'
      , '  <div class="fl-content">'
      , '    <div class="flow-info">'
      , '        <p>{{ (d.flow_brief ? d.flow_brief.substring(0, 24) :"") || (d.brief ? d.brief.substring(0, 24) :"") || "" }}</p>'
      , '        <p class="info-m">〔{{ d.put_dept_id_name }}〕{{ d.put_name }} {{  d.create_time > 0 ? timeChange(d.create_time) : "" }}</p>'
      , '    </div>'
      , '  </div>'
      , '  <div class="fl-right">'
      , '    <div class="flow-time">'
      , '      <p>{{- statusTd(d.step_id_status_val) }}</p>'
      , '      <p>{{ d.now_audit_name }}</p>'
      , '    </div>'
      , '  </div>'
      , '</div>'
    ].join(''),
    //系统消息内容盒子
    sysmsgTpl = ['<div class="sz-sysmsgbox"></div>'].join(''),
    //系统消息内容
    sysmsgrowTpl = ['<div class="sysmsg-row {{ d.status ==1 ? " " : " ithis " }}" szim-event="sysmsgRow" id="sysmsg_msg_{{ d.id }}" data-id="{{ d.id }}" data-url="{{ d.m_url }}">'
      , '  <div class="fl-left"><span class="sysmsg-badge">{{ d.modu_name ? d.modu_name.substring(0, 4) : "" }}</span></div>'
      , '  <div class="fl-content">'
      , '    <div class="sysmsg-info">{{ d.brief ? d.brief.substring(0, 20) : "" }}</div>'
      , '  </div>'
      , '  <div class="fl-right">'
      , '    <div class="sysmsg-time">'
      , '      {{# if(d.send_id_name){ }}<p><span class="layui-badge layui-bg-blue">{{ d.send_id_name }}</span></p>{{# } }}'
      , '      <p>{{  d.create_time > 0 ? timeChange(d.create_time) : "" }}</p>'
      , '    </div>'
      , '  </div>'
      , '</div>'
    ].join(''),
    //聊天对象列表row
    chatObjRowTpl = ['<div class="kg-row kg-cli szimchatobj" data-oid="{{ d.oid || 0}}" data-chattype="{{ d.chat_type || 0}}" data-id="{{ d.id || 0 }}" szim-event="ToSend">'
      , '<div class="kg-col kg-w40m5">'
      , '  <img class="cli-avatar" src="{{ d.avatar || "" }}" alt="头像" />'
      , '  <span id="badge_{{ d.id || "" }}" class="szim-badge {{ d.badge > 0 ? "" : "layui-hide" }}">{{ d.badge || 0 }}</span>'
      , '</div>'
      , '<div class="kg-col kg-w100">'
      , '  <div class="kg-title">{{ d.name || "" }}</div>'
      , '  <div class="kg-brief nowrap" id="brief_{{ d.id || "" }}">{{ d.content ? d.content.substring(0, 10) : "" }}</div>'
      , '</div>'
      , '<div class="kg-col kg-w40">'
      , '  <div class="kg-hhss" id="time_{{ d.id || "" }}">{{ d.create_time ? timeChange(d.create_time) : "" }}</div>'
      , '  <div class="kg-dnd"></div>'
      , '</div>'
      , '</div>'].join(''),
    //群对象列表
    groupObjListTpl = ['<div class="kg-row kg-cli" data-id="{{ d.group_id }}" szim-event="groupToSend">'
      , '<div class="kg-col kg-w40m5">'
      , '  <img class="cli-avatar" src="{{ d.avatar }}" alt="头像" />'
      , '</div>'
      , '<div class="kg-col kg-w100">'
      , '  <div class="kg-title">{{ d.group_name }}</div>'
      , '</div>'
      , '</div>'].join(''),
    //通知盒子
    notifyTpl = ['<div class="sz-notify topcenter" id="szNotify">', '</div>'].join(''),
    //通知模板
    notifyMsgTpl = ['<div class="notify-row notify-info" id="{{d.szid}}">'
      , '  <div class="notify-col"><i class="{{ d.msgType.info }}"></i></div>'
      , '  <div class="notify-col">{{ d.msg }}</div>'
      , '  <div class="notify-col"><i class="{{ d.close }}" id="close_notify_{{d.szIndex}}"></i></div>'
      , '</div>'].join('');

  var TipsType = { tipsNormal: "tips", tipsPrimary: "tips-primary", tipsSuccess: "tips-success", tipsInfo: "tips-info", tipsWarning: "tips-warning", tipsDanger: "tips-danger" },//提示消息类型对应的样式
    TitleType = { admin: "admin", owner: "owner" },//对话标题类型--群才会用到
    checkURL = function (a) { return 1 == new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/).test(a) ? !0 : !1; },
    focusInsert = function (c) {
      var a = $('.chatinput')[0];
      var b = a.value; a.focus();
      document.selection ? ((b = document.selection.createRange()), document.selection.empty(), (b.text = c)) :
        ((b = [b.substring(0, a.selectionStart), c, b.substr(a.selectionEnd)]), a.focus(), (a.value = b.join("")))
    },//在焦点处插入内容
    beforeRenderingHTML = function (b, a) {//渲染聊天记录-实时
      var d = "", c = document.querySelector(a);
      for (a = 0; a < b.length; a++)
        b[a].isRender ||
          ((d = -1 !== b[a].messageType.indexOf("tips") // 是否提示消息
            ? d + renderTipHtml(b[a].content, TipsType[b[a].messageType] || "tips") //渲染提示消息
            : d + renderMessageHtml(b[a])), // 渲染对话消息
            (b[a].isRender = !0));//记录已渲染
      c.insertAdjacentHTML("beforeend", d);//在结束之前插入
      setTimeout(function () {// 滚动到底部
        c.scrollHeight > c.clientHeight && ((c.scrollTop = c.scrollHeight), (d = c = ""));
      }, 100);
    },
    renderMessageHtml = function (a) {// 渲染对话消息
      return '<div class="'.concat(a.mine ? "cright" : "cleft", ' cmsg">')
        .concat('<img class="headIcon ', a.diamond ? "radius" : "", '" src="', a.avatar, '" ondragstart="return false;" oncontextmenu="return false;"/>')
        .concat('<span class="name">', renderTitleHtml(a.highText, TitleType[a.titleHigh] || ""))
        .concat('<span>', (a.mine ? formatDateTime(a.create_time) + ' ' + escapeHtml(a.name) : escapeHtml(a.name) + ' ' + formatDateTime(a.create_time)), '</span>')
        .concat('</span>', '<span class="content">', contentFormat(a.content), "</span></div>");
    },
    //渲染标题
    renderTitleHtml = function (a, b) { return a ? '<span class="highText '.concat(b, '" style="margin: 0 4px 0 0;">').concat(a, "</span>") : "" },
    //渲染提示消息
    renderTipHtml = function (a, b) { return a ? '<div class="tips"><span class="'.concat(b, '" style="margin-bottom: 20px;">').concat(contentFormat(a), "</span></div>") : "" },
    escapeHtml = function (a) { return null === a || void 0 === a ? void 0 : a.replace(/[\u0000-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u00FF]/g, function (b) { return "&#" + ("000" + b.charCodeAt(0)).slice(-4) + ";" }) },
    voice = function () { //消息声音提醒
      if (layui.device.ie && layui.device.ie < 9) return;
      var audio = document.createElement("audio");
      audio.src = '/static/video/message.mp3';
      audio.play();
    },
    selfchat = function () { layer.msg('亲，聊天得去找个对象！禁止自己玩！！！') },
    // 发送消息
    sendMessage = function () {
      if (!cache.mine || !cache.mine.id) { layer.msg('数据丢失，请重新加载！'); };
      var data = {
        username: cache.mine.username || ''
        , avatar: cache.mine.avatar || szoapcpath + ('/static/img/default.png')
        , id: cache.mine.id || 0
        , mine: 1
      };
      var thatInput = $('.chatinput');
      var maxLength = 4000;
      var To = current.chatObj; //当前聊天对象
      data.content = thatInput.val();//当前聊骚内容
      if (data.content.replace(/\s/g, '') !== '') {
        if (data.content.length > maxLength) {
          return layer.msg('内容最长不能超过' + maxLength + '个字符');
        }
        //发送云端数据
        var sendata = {
          type: 'chat',
          formId: data.id,
          content: data.content,
          contype: 'text',
        };
        //PC版需要解析一下 text,img,video,file=>other
        if (data.content.substring(0, 4) == 'img[') {
          sendata.contype = 'img';
          tmpurl = data.content.replace(/(^img\[)|(\]$)/g, '');
          sendata.files_url = tmpurl;
          sendata.content = '';
        } else if (data.content.substring(0, 6) == 'video[') {
          tmpurl = data.content.replace(/(^video\[)|(\]$)/g, '');
          sendata.files_url = tmpurl;
          sendata.contype = 'video';
          sendata.content = '';
        } else if (data.content.substring(0, 5) == 'file(') {
          str = data.content;
          tmpurl = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
          var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
          sendata.files_url = tmpurl;
          sendata.contype = 'other';
          sendata.content = text;
        }

        switch (current.chatType) {
          case 1:
            sendata.toId = To.id;
            break;
          case 2:
            sendata.group_id = To.group_id;
            break;
        }
        sendata.chat_type = current.chatType;
        if (data.id == To.id) {
          selfchat();
          return;
        }
        //远送云端
        sendWSPush(sendata);
      };
      thatInput.val('').focus();
    },
    // 消息对象列表-格式化
    chatObjListFormat = function (d) {
      var list = [];
      layui.each(d, function (i9, e9) {
        var tmp = chatObjFormat(e9);
        if (typeof (tmp) != "undefined") {
          list.push(tmp);
        }
      });
      return list;
    },
    //消息对象--格式化(统一) 聊天时也统一此法解析
    chatObjFormat = function (d) {
      var li = Object.assign({}, d); //先克隆
      if (!d.chat_type) {
        layer.msg('不支持的消息类型！');
        return !1;
      };
      li = Object.assign(li, {
        chat_type: d.chat_type,
        create_time: d.create_time || 0,
        content: d.content || '',
        badge: d.badge || 0,
      });
      switch (d.chat_type) {
        case 1:
          li.id = (d.send_id == cache.mine.id ? d.rece_id : (d.rece_id == cache.mine.id ? d.send_id : 0));
          li.avatar = (d.send_id == cache.mine.id ? d.rece_id_avatar : (d.rece_id == cache.mine.id ? d.send_id_avatar : ''));
          li.name = (d.send_id == cache.mine.id ? d.rece_id_name : (d.rece_id == cache.mine.id ? d.send_id_name : ''));
          li.oid = li.id;
          li.id = 'id_' + d.chat_type + '_' + li.id;
          break;
        case 2:
          li.id = d.group_id;
          li.avatar = d.avatar || d.group_id_avatar || '';
          li.name = d.group_id_name;
          li.oid = li.id;
          li.id = 'id_' + d.chat_type + '_' + li.id;
          break;
        case 3:
          li.id = d.id;
          li.avatar = d.avatar || '';
          li.name = d.name || "流程消息";
          li.content = d.flow_brief || '';
          li.oid = li.id;
          li.id = 'id_' + d.chat_type + '_' + li.id;
          break;
        case 4:
          li.id = d.id;
          li.avatar = d.avatar || '';
          li.name = d.name || "系统消息";
          li.content = d.content || '';
          li.oid = li.id;
          li.id = 'id_' + d.chat_type + '_' + li.id;
          break;
        default:
          li.id = 0; // 为0就会过滤掉
          break;
      }
      return li;
    },
    //解析对象列表
    parseObjList = function (a, d) {
      var b = "";
      a &&
        layui.each(a, function (e, c) {
          b += laytpl(d).render(c);
        });
      return b;
    },
    // 移除历史聊天记录窗
    removechatlogbox = function () {
      var objbox = $(elemimbox);
      var selobj = $('#chatlogbox');
      var ow = objbox.width();
      if (selobj.length > 0) {
        selobj.remove();
        if (ow <= 1200 && ow > 750) {
          objbox.animate({ 'width': '750px' }, 300);
        }
        objbox.find('.chat-col-3').css('width', 'calc(100% - 261px)');
        if (parseFloat(objbox.css('left')) > $(window).width() - 760) {
          objbox.animate({ 'left': $(window).width() - 760 }, 300);
        }
        current.isShowLog = false;
      }
    },
    findIdInTree = function (id, tree) {
      layui.each(tree, function (i9, e9) {
        if (typeof e9.children === "undefined" && e9.id == id) {
          current.intree = e9;
        } else {
          current.intree = findIdInTree(id, e9.children);
        }
      });
      return current.intree;
    },
    contentTypeTIVA = function (d) {
      var out = '';
      switch (d) {
        case 'text':
        case 'img':
        case 'video':
        case 'other':
          out = 'text';
          break;
        default:
          out = d;
          break;
      }
      return out;
    },
    inChatObjList = function (d, b) {
      var getobj = chatObjFormat(d);
      var is_in = false;
      if (cache.chat.length > 0) {
        layui.each(cache.chat, function (i9, e9) {
          if (d.chat_type == 1 && e9.id == getobj.oid) {
            is_in = true;
          } else if (d.chat_type == 2 && e9.group_id == getobj.group_id) {
            is_in = true;
          }
        });
      }
      if (is_in) { //存在，直接加数字
        if (b === 0) {
          objLibadge(getobj, 0);
        }
      } else {
        cache.chat.splice(2, 0, getobj);
        var icont = icont = laytpl(chatObjRowTpl).render(getobj);
        $('#id_3_3').after(icont);//固定在流程信息之后插入
        if (b === 0) {
          objLibadge(getobj, 0);
        }
      }
    },
    //接收消息
    getMessage = function (data) {
      var is_room = false;//关门(防串门)
      data = data || {};
      switch (data.chat_type) {
        case 4://系统消息
          data.mine = 0;
          // console.log('接收消息---系统消息');
          // console.log(data);
          if ($.inArray(data.id, sysmsg.ids) == -1) {//添加
            sysmsg.ids.push(data.id);
            sysmsg.list.push(data);
            if (cache.base.is_voice) { //新的系统消息，播音
              voice();
            }
          }
          if ($('.sz-sysmsgbox').length > 0) { // 当前是系统消息 对象窗
            layui.each(sysmsg.list, function (i3, e3) {
              if (sysmsg.list[i3].isRender !== 1) {
                $('.sz-sysmsgbox').prepend(laytpl(sysmsgrowTpl).render(e3));
                sysmsg.list[i3].isRender = 1;
                sysmsgRowContextmenu(e3.id);
              }
            });
          } else {
            var libadge = $('#badge_id_4_4');
            var lbnum = 0;
            layui.each(sysmsg.list, function (i2, e2) {
              if (e2.status == 1) { //状态为1的才是新消息
                lbnum++;
              }
            });
            if (lbnum > 0) {
              libadge.removeClass(hidecss);
              libadge.html(lbnum);
            } else {
              libadge.addClass(hidecss);
              libadge.html(0);
            }
          }
          break;
        case 3://流程消息
          data.mine = 0;
          if ($.inArray(data.id, flow.ids) == -1) {//添加
            flow.ids.push(data.id);
            flow.list.push(data);
            if (cache.base.is_voice) { //新的流程消息，播音
              voice();
            }
          }
          if ($('.sz-flowbox').length > 0) { // 当前是系统消息 对象窗
            layui.each(flow.list, function (i3, e3) {
              if (flow.list[i3].isRender !== 1) {
                $('.sz-flowbox').prepend(laytpl(flowrowTpl).render(e3));
                flow.list[i3].isRender = 1;
                flowRowContextmenu(e3.id);
              }
            });
          } else {
            var libadge = $('#badge_id_3_3');
            var lbnum = 0;
            layui.each(flow.list, function (i2, e2) {
              if (e2.status == 1) { //状态为1的才是新消息
                lbnum++;
              }
            });
            if (lbnum > 0) {
              libadge.removeClass(hidecss);
              libadge.html(lbnum);
            } else {
              libadge.addClass(hidecss);
              libadge.html(0);
            }
          }
          break;
        case 1://单聊
        case 2://群聊
          if (data.send_id == cache.mine.id) {
            data.mine = 1; //右边
          } else {
            data.mine = 0;
          }
          if (cache.base.is_voice && data.mine == 0) {
            voice();
          }
          data.content = contentTIVA(data);
          if (current.chatObj && JSON.stringify(current.chatObj) === "{}") {//空对象，当前没有聊天对象窗
            //判断是否已存在 消息对象列表里，没有则添加
            inChatObjList(data, 0);
          } else {//当前有聊天对象窗
            //判断房间，不能串台..
            if (data.chat_type == 1) { //单聊
              // 我发送的他接收的，他发送的我接收的
              if (current.chatObj && current.chatObj.id && (
                (data.send_id == cache.mine.id && data.rece_id == current.chatObj.id) ||
                (data.rece_id == cache.mine.id && data.send_id == current.chatObj.id)
              )
              ) {
                is_room = true;
              }
            } else if (data.chat_type == 2) {//群聊
              // 群对应上
              if (current.chatObj && current.chatObj.group_id && data.group_id == current.chatObj.group_id) {
                is_room = true;
              }
            }
            if (is_room) {//确定房间
              inChatObjList(data, 1);
              var pud = {
                messageType: contentTypeTIVA(data.content_type),
                avatar: data.send_id_avatar,
                name: data.send_id_name,
                mine: data.mine,
                content: data.content,
                create_time: data.create_time
              };
              current.chatData.push(pud);
              beforeRenderingHTML(current.chatData, '.sz-chatbox');
              //如果历史记录窗有开启
              var selobj = $('#chatlogbox');
              if (selobj.length > 0) {
                current.chathis.push(pud);
                beforeRenderingHTML(current.chathis, '.szimchatlog');
              }
            } else {
              inChatObjList(data, 0);
            }
          }
          break;
      }
      minbadgenum();
      //回调
      typeof (data.callback) === "function" && data.callback(JSON.parse(JSON.stringify(data)), cache);
    },
    badgecount = function () {
      var ttn = 0;
      $('.szim-badge').each(function (i, m) {
        ttn += parseInt($(m).html());
      });
      return ttn;
    },
    //右下角通知数
    minbadgenum = function () {
      var bcount = badgecount();
      $('#szim-min-badge').html(bcount);
      if (bcount < 1) {
        $('#szim-min-badge').addClass(hidecss);
      } else {
        $('#szim-min-badge').removeClass(hidecss);
      }
    },
    //移除红点数字
    removeobjLibadge = function (d) {
      var libadge;
      if ($.isNumeric(d.id)) {
        if (d.chat_type == 2) {
          libadge = $('#badge_id_' + d.chat_type + '_' + d.group_id);
        } else {
          libadge = $('#badge_id_' + d.chat_type + '_' + d.id);
        }
      } else {
        libadge = $('#badge_' + d.id);
      }
      libadge.html(0);
      libadge.addClass(hidecss);
    },
    //添加红点数字
    objLibadge = function (d, n) {
      var libadge = $.isNumeric(d.id) ? $('#badge_id_' + d.chat_type + '_' + d.id) : $('#badge_' + d.id);
      libadge.removeClass(hidecss);
      if (n) {
        libadge.html(n);
      } else {
        var now_num = parseInt(libadge.html());
        now_num++;
        libadge.html(now_num);
      }
      if (d.chat_type != 3) {
        $('#brief_id_' + d.chat_type + '_' + d.id).html((d.content ? d.content.substring(0, 11) : ""));
        $('#time_id_' + d.chat_type + '_' + d.id).html(timeChange(d.create_time));
      }
    },
    sysmsgRowContextmenu = function (id) {
      //右键菜单
      dropdown.render({
        elem: '#sysmsg_msg_' + id
        , trigger: 'contextmenu'
        , isAllowSpread: false
        , style: 'width: 200px'
        , id: 'smg_id_' + id
        , data: [{ title: '删除', id: 'smg_id_' + id }]
        , click: function (obj, othis) {
          if (obj.id === 'smg_id_' + id) {
            $.post(cache.base.delmsgUrl, { id: id, issys: 1 }, function (res7) {
              layer.msg(res7.msg);
              if (res7.status) {
                $('#sysmsg_msg_' + id).empty().remove();
                layui.each(sysmsg.list, function (i3, e3) {
                  if (e3.id == id) {
                    sysmsg.list.remove(e3);
                  }
                });
              }
            });
          }
        }
      });
    },
    flowRowContextmenu = function (id) {
      //右键菜单
      dropdown.render({
        elem: '#flow_msg_' + id
        , trigger: 'contextmenu'
        , isAllowSpread: false
        , style: 'width: 200px'
        , id: 'frc_id_' + id
        , data: [{ title: '删除', id: 'frc_id_' + id }]
        , click: function (obj, othis) {
          if (obj.id === 'frc_id_' + id) {
            $.post(cache.base.delmsgUrl, { id: id }, function (res7) {
              layer.msg(res7.msg);
              if (res7.status) {
                $('#flow_msg_' + id).empty().remove();
                layui.each(flow.list, function (i3, e3) {
                  if (e3.id == id) {
                    flow.list.remove(e3);
                  }
                });
              }
            });
          }
        }
      });
    },
    //拖动窗体-及事件
    dragEvent = function (o) {
      var dragobj = $(elemimbox); //要拖动的对象
      var tfobj = dragobj.find(o); //触发拖动的区域
      tfobj.mousedown(function (e) {
        //鼠标按下时触发
        if (e.button) {
          return;
        } // 不是左键不处理
        szwin.move = true;
        szwin.winX = parseFloat(dragobj.css("width")) + 10;
        szwin.winY = parseFloat(dragobj.css("height")) + 10;
        szwin._x = e.pageX - parseFloat(dragobj.css("left"));
        szwin._y = e.pageY - parseFloat(dragobj.css("top"));
        document.onselectstart = function () {
          return false;
        };
        //加遮罩层
        $("body").append('<div class="move-mark" szim-mark></div>');
        e.preventDefault();
      });
      $(document)
        .mousemove(function (e) {
          //鼠标移动时
          if (szwin.is_max) {
            //最大化时不可移动
            szwin.move = false;
            document.onselectstart = function () {
              return true;
            };
            return;
          }
          if (szwin.move) {
            var x = e.pageX - szwin._x;
            var y = e.pageY - szwin._y;
            //不能超出区域
            if (x < 10) {
              x = 10;
            }
            if (y < 10) {
              y = 10;
            }
            if (x > szwin.maxW - szwin.winX) {
              x = szwin.maxW - szwin.winX;
            }
            if (y > szwin.maxH - szwin.winY) {
              y = szwin.maxH - szwin.winY;
            }
            dragobj.css("top", y);
            dragobj.css("left", x);
          }
        })
        .mouseup(function () {
          szwin.move = false;
          document.onselectstart = function () {
            return true;
          };
          $("[szim-mark]").remove();
        });
    },
    //解析内容类型--兼容MP端
    contentTIVA = function (d) {
      if (!d) return '';
      var content = '';
      switch (d.content_type) {
        case 'text':
          content = d.content;
          break;
        case 'img':
          content = 'img[' + d.files_url + ']';
          break;
        case 'video':
          content = 'video[' + d.files_url + ']';
          break;
        case 'other':
          content = 'other(' + d.files_url + ')[' + d.content + ']';
          break;
      }
      return content;
    },
    // 聊天面板 数据渲染
    renderContent = function (d) {
      if (!d) return '';
      var rcd = [];
      layui.each(d, function (i9, e9) {
        if (cache.mine && cache.mine.id) {
          var content = contentTIVA(e9);
          var tmpd = {
            messageType: e9.content_type,
            avatar: e9.send_id_avatar,
            name: e9.send_id_name,
            content: content,
            create_time: e9.create_time,
          };
          //我发送的
          if (cache.mine.id == e9.send_id) {
            tmpd.mine = 1;
          } else { //别人发送的
            tmpd.mine = 0;
          }
          rcd.push(tmpd);
        }
      });
      return rcd;
    },
    //快捷键发送
    hotkeySend = function () {
      var textarea = $('.chatinput');
      textarea.focus();
      textarea.off('keydown').on('keydown', function (e) {
        var keyCode = e.keyCode;
        if (e.ctrlKey && keyCode === 13) {
          sendMessage();
          return;
        }
      });
    },
    //聊天内容渲染
    listRender = function (d) {
      //转化所需的数据格式
      current.chatData = []; //每切换对象清空一次
      current.chatData = renderContent(d);
      //载入历史记录，倒序
      current.chatData = current.chatData.reverse();
      beforeRenderingHTML(current.chatData, '.sz-chatbox');
    },
    //用户聊骚面板渲染
    userChat = function (d) {
      // console.log(d);
      if (typeof (d.chat_type) === "undefined") {
        layer.msg('不支持的聊天类型！');
        return;
      }
      if (d.chat_type == 1) { //单聊
        if (cache.mine.id == d.id) {
          selfchat();
          return;
        }
        $('.kg-content').empty().append(contentTpl).show();
        $('.kg-user-title').html(d.name);
        //单聊取历史记录20条
        $.get(cache.base.userhisUrl, { rid: d.id, read: 1 }, function (res) {
          if (res.code == 0) {
            listRender(res.data);
          }
        });
      } else if (d.chat_type == 2) {//群聊
        $('.kg-content').empty().append(contentTpl).show();
        $('.kg-user-title').html('<span class="layui-badge layui-bg-blue">群聊</span> ' + (d.group_name || d.name || ""));
        //群聊取历史记录20条
        $.get(cache.base.qunhisUrl, { group_id: d.group_id }, function (res) {
          if (res.status) {
            listRender(res.data);
          }
        });
      } else {
        layer.msg('不支持其它聊骚方式！！！');
        return;
      }
      hotkeySend();
    },
    groupgetobj = function (group_id) {
      var out = {};
      layui.each(cache.group, function (i9, e9) {
        if (e9.group_id == group_id) {
          out = e9;
        }
      });
      if (out) {
        current.chatObj = out; //当前对象
        removeobjLibadge(current.chatObj);//打开聊天面板后，清除红点
        userChat(current.chatObj);
      }
    },
    friendgetobj = function (id) {
      var out = findIdInTree(id, cache.friend);
      if (!$.isEmptyObject(out)) {
        if (out.id == id) {//不能串台了
          current.chatObj = out;
          removeobjLibadge(current.chatObj);//打开聊天面板后，清除红点
          userChat(out);
        }
      }else{
        layer.msg('用户被禁用或不存在了');
      }
    },
    flowrender = function () {
      layui.each(flow.list, function (i3, e3) {
        $('.sz-flowbox').prepend(laytpl(flowrowTpl).render(e3));
        flow.list[i3].isRender = 1;
        flowRowContextmenu(e3.id);
      });
    },
    sysmsgrender = function () {
      layui.each(sysmsg.list, function (i3, e3) {
        $('.sz-sysmsgbox').prepend(laytpl(sysmsgrowTpl).render(e3));
        sysmsg.list[i3].isRender = 1;
        sysmsgRowContextmenu(e3.id);
      });
    };

  var init = function (o) {
    var icb = $(elemimbox);
    if (icb.length > 0) {
      icb.empty().remove(); //存在则销毁移除
    }
    //取数据
    if (o.initUrl) {
      $.get(o.initUrl, function (res) {
        if (res.status) {
          var rd = res.data;
          cache.mine = rd.mine;
          cache.chat = rd.chatobj.list;
          cache.friend = rd.friend;
          cache.group = rd.group;
          cache.chat.unshift({
            id: 4,
            chat_type: 4,
            avatar: '/static/img/sys/default.png',
            badge: 0,
            name: '系统消息',
            content: '',
            create_time: 0
          }, {
            id: 3,
            chat_type: 3,
            avatar: '/static/img/flow/default1.png',
            badge: 0,
            name: '流程消息',
            content: '',
            create_time: 0
          });
          o.avatar = rd.mine.avatar || o.avatar;

          //组装模板
          var data = $.extend({
            btns: laytpl(btnTpl).render(o),
            set: laytpl(setTpl).render(o),
            search: laytpl(searchTpl).render(o),
            list: parseObjList(chatObjListFormat(cache.chat), chatObjRowTpl),
            group: parseObjList(cache.group, groupObjListTpl),
            content: ''
          }, o);

          //渲染开始
          laytpl(mainTpl).render(data, function (html) {
            $('body').append(html);
            $('.szim-minbtn').hide();//缩小窗
            dragEvent(".tf-head");//拖动
            //默认
            $('.win-restore').hide();
            $('.kg-dept').hide();
            //默认没有聊天对象
            $('.kg-content').hide();

            //部门人员点击 -- 这个事件只能用imtree里的。
            imtree.render({
              elem: '.kg-deptuser' //默认是点击节点可进行收缩
              , data: cache.friend
              , showLine: false
              , click: function (treeobj) {
                removechatlogbox();
                //缓存当前节点数据--与 对象 的数据
                current.chatObj = treeobj.data;
                current.chatType = 1;
                userChat(current.chatObj);
              }
            });
            //查看大图
            $(elemimbox).on('dblclick', '.szim-photos', function () {
              var src = this.src;
              layer.photos({
                photos: {
                  data: [{
                    "alt": "大图模式",
                    "src": src
                  }]
                }
                , shade: 0.01
                , closeBtn: 2
                , anim: 0
                , resize: false
                , success: function (layero, index) {
                  photosIndex = index;
                }
              });
            });
          });
        }
      });
    }
  },
    wingomin = function () {
      $(elemimbox).hide(300);
      $(minbox.btn).show(300);
      var mbo = $(minbox.badge);
      if (cache.badgeCount < 1) {
        mbo.addClass(hidecss);
      } else {
        mbo.html(cache.badgeCount).removeClass(hidecss);
      }
    }, wingostore = function () {
      $(elemimbox).show(300);
      $(minbox.btn).hide(300);
      $(minbox.badge).html(0).addClass(hidecss);
    },
    events = {
      winmax: function (elem, e) {
        var obj = $(elemimbox);
        var w100 = $(window).width() - 20;
        var h100 = $(window).height() - 20;
        szwin.old_x = parseFloat(obj.css('left'));
        szwin.old_y = parseFloat(obj.css('top'));
        obj.css({ 'left': 10, 'top': 10, 'width': w100, 'height': h100 });
        szwin.is_max = true;
        $('.win-restore').show();
        $('.win-max').hide();
      },
      winrestore: function (e) {
        var obj = $(elemimbox);
        if (current.isShowLog) {
          if (szwin.old_x > $(window).width() - 1210) {
            szwin.old_x = $(window).width() - 1210
          }
          obj.css({ 'left': szwin.old_x, 'top': szwin.old_y, 'width': 1200, 'height': 520 });
          $('.win-restore').hide();
          $('.win-max').show();
          szwin.is_max = false;
        } else {
          if (szwin.old_x > $(window).width() - 760) {
            szwin.old_x = $(window).width() - 760
          }
          obj.css({ 'left': szwin.old_x, 'top': szwin.old_y, 'width': 750, 'height': 520 });
          $('.win-restore').hide();
          $('.win-max').show();
          szwin.is_max = false;
        }
      },
      winmin: function (e) {
        wingomin();
      },
      winclose: function (e) {
        wingomin();
      },
      szimminbtn: function () {//最小化后的事件
        wingostore();
      },
      hlight: function (elem, e) {//高亮切换
        var html = document.getElementById('imchatbox');
        var theme = html.getAttribute("szwebchat-theme");
        if (theme === 'dark') {
          html.setAttribute("szwebchat-theme", 'light');
        } else {
          html.setAttribute("szwebchat-theme", 'dark');
        }
      },
      about: function (elem, e) {//关于
        layer.tips('盛筑即时通讯(SZIM)<br/>版本：v' + version + '', elem, {
          tips: 1
        });
      },
      cutchatmessage: function (elem, e) {
        $('.kg-list').show();
        $('.kg-dept').hide();
        $('#chatuserlist>i').removeClass('szthis');
        $('#chatmessage>i').addClass('szthis');
      },
      cutchatuserlist: function (elem, e) {
        $('.kg-list ').hide();
        $('.kg-dept').show();
        $('#chatmessage>i').removeClass('szthis');
        $('#chatuserlist>i').addClass('szthis');
      },
      face: function (elem, e) {//表情
        var content = '';
        for (var key in faces) {
          content += '<li title="' + key + '"><img src="' + faces[key] + '"></li>';
        }
        content = '<ul class="layui-clear szim-face-list">' + content + '</ul>';
        var faceindex = layer.tips(content, elem, {
          tips: 1
          , time: 0
          , fixed: true
          , skin: 'layui-box layui-szim-face'
          , success: function (layero) {
            layero.find('.szim-face-list>li').on('mousedown', function (e) {
              stope(e);
            }).on('click', function (ev) {
              focusInsert('face' + this.title + ' ');
              layer.close(faceindex);
            });
          }
        });
        var faceHide = function () { layer.close(faceindex); }
        $(document).off('mousedown', faceHide).on('mousedown', faceHide);
        $(window).off('resize', faceHide).on('resize', faceHide);
        stope(e);
      },
      image: function (elem, e) {
        var type = elem.data('type') || 'images';
        window.file_win_layid = layer.open({
          type: 2,
          title: '<i class="fa fa-upload"></i> 上传文件',
          shade: 0.5,
          area: ['90%', '90%'],
          content: szoa.client.path + '/pages/files/upfiles.html?id=7',
          success: function (layero, index) {
            window.file_info = function (opt) {
              if (opt) {
                if (type === 'images') {
                  focusInsert('img[' + (opt.url || '') + ']');
                } else if (type === 'file') {
                  focusInsert('file(' + (opt.url || '') + ')[' + (opt.other.name || '下载文件') + ']');
                }
                sendMessage();
                layer.close(window.file_win_layid);
              }
            };
          }
        });
      },
      media: function (elem, e) {
        var type = elem.data('type');
        window.file_win_layid = layer.open({
          type: 2,
          title: '<i class="fa fa-upload"></i> 上传文件',
          shade: 0.5,
          area: ['90%', '90%'],
          content: szoa.client.path + '/pages/files/upfiles.html?id=7',
          success: function (layero, index) {
            window.file_info = function (opt) {
              if (opt) {
                focusInsert(type + '[' + opt.url + ']');
                sendMessage();
                layer.close(window.file_win_layid);
              }
            };
          }
        });
      },
      playVideo: function (elem, e) {
        var videoData = elem.data('src'), video = document.createElement('video');
        if (!video.play) {
          return layer.msg('您的浏览器不支持video');
        }
        layer.open({
          type: 1
          , title: '播放视频'
          , area: ['960px', '640px']
          , maxmin: true
          , shade: 0.1
          , content: '<div style="background-color: #000; height: 100%;">\
        <video style="position: absolute; width: 100%; height: 100%;" src="' + videoData + '"  controls muted loop="loop" autoplay="autoplay">\
        </video></div>'
        });
      },
      website: function (elem, e) {
        layer.tips(['<div class="layui-form" lay-filter="szim-a-form">',
          '<div class="tips-abox"><input type="text" name="szimaurl" lay-verify="required" placeholder="URL(例：https://qzszoa.com)" lay-reqText="URL必须填写,并以http开头" class="layui-input"></div>',
          '<div class="tips-abox"><input type="text" name="szimaname" placeholder="要显示的名称" class="layui-input"></div>',
          '<div class="tips-abox"><button class="layui-btn layui-btn-normal" lay-submit lay-filter="szim-aform-submit">确定</button>',
          '<button class="layui-btn layui-btn-danger szim-aform-cancel">取消</button></div>',
          '</div>'].join(''),
          elem,
          {
            tips: 1,
            time: 0,
            area: ['360px', '150px'],
            success: function (layero, index) {
              $('.szim-aform-cancel').off('click').on('click', function (e) {
                layer.closeAll('tips');
              });
              form.on('submit(szim-aform-submit)', function (data) {
                var d = data.field;
                if (d.szimaurl && checkURL(d.szimaurl)) {
                  focusInsert('a(' + d.szimaurl + ')[' + (d.szimaname || d.szimaurl) + ']');
                  layer.close(index);
                } else {
                  layer.msg('必须填写正确的URL，以http/https开头');
                }
                return false;
              });
            },
          });
      },
      chatLog: function (elem, e) {
        var objbox = $(elemimbox);
        var rowbox = $('#chatrowbox');
        var selobj = $('#chatlogbox');
        var ow = objbox.width();
        if (selobj.length > 0) {
          selobj.remove();
          if (ow <= 1200 && ow > 750) {
            objbox.animate({ 'width': '750px' }, 300);
          }
          objbox.find('.chat-col-3').css('width', 'calc(100% - 261px)');
          if (parseFloat(objbox.css('left')) > $(window).width() - 760) {
            objbox.animate({ 'left': $(window).width() - 760 }, 300);
          }
          current.isShowLog = false;
        } else {
          if (ow < 800) {
            objbox.animate({ 'width': '1200px' }, 300);
          }
          if (parseFloat(objbox.css('left')) > $(window).width() - 1210) {
            objbox.animate({ 'left': $(window).width() - 1210 }, 300);
          }
          objbox.find('.chat-col-3').css('width', 'calc(100% - 711px)');
          var logsearch = '<div class="chatloghead"><span id="chatlogtitle"></span></div>'; //<span><input type="text" class="logsearchinput" placeholder="搜索" /></span>
          rowbox.append('<div class="chat-col-4" id="chatlogbox">' + logsearch + '<div class="szimchatlog"></div></div>');
          current.isShowLog = true;
          current.chathis = [];//清空 当前聊天历史记录
          setTimeout(function () {
            var hisurl = '';
            switch (current.chatType) {
              case 1:
                hisurl = cache.base.userhisUrl;
                break;
              case 2:
                hisurl = cache.base.qunhisUrl;
                break;
              default:
                hisurl = '';
                break;
            }
            if (hisurl == '') {
              layer.msg('出错了，请重新加载');
              return;
            }
            var ud = {
              page: current.page,
              limit: current.limit,
              rid: current.chatObj.id || 0,
              group_id: current.chatObj.group_id || 0
            };
            $.get(hisurl, ud, function (res2) {
              if (res2.code == 0) {
                //转化所需的数据格式
                current.chathis = renderContent(res2.data, 3);
                var isPages = false;
                if (res2.pages > res2.page) {
                  isPages = true;
                  current.chathis.unshift({
                    messageType: 'tipsNormal',
                    content: 'span[加载更多]'
                  });
                }
                //载入历史记录
                current.chathis = current.chathis.reverse();
                beforeRenderingHTML(current.chathis, '.szimchatlog');
                if (isPages) {
                  $('.load-pages').on('click', function (e) {
                    layer.msg('加载分页....');
                  });
                }
              }
            });
            current.chatType == 1 ?
              $('#chatlogtitle').html('与 ' + (current.chatObj.name || '') + ' 的聊天记录') :
              $('#chatlogtitle').html('群： ' + (current.chatObj.group_name || '') + ' 的聊天记录');
          }, 50);
        }
      },
      ToSend: function (elem, e) {//对象列表里的行事件
        removechatlogbox();
        $('.szimchatobj').removeClass('im-this');
        elem.addClass('im-this');
        var id = elem.attr('data-oid');
        var chattype = parseInt(elem.attr('data-chattype'));
        switch (chattype) {
          case 4://系统消息
            current.chatType = 4;
            current.chatObj = cache.chat[0];//第1个
            if ($('.sz-sysmsgbox').length < 1) {
              $('.kg-content').empty().append(sysmsgTpl).show();
            }
            $('.kg-user-title').html('系统消息');
            removeobjLibadge(current.chatObj);
            $('.sz-sysmsgbox').empty();
            sysmsgrender();
            break;
          case 3://流程
            current.chatType = 3;
            current.chatObj = cache.chat[1];//第2个
            if ($('.sz-flowbox').length < 1) {
              $('.kg-content').empty().append(flowTpl).show();
            }
            $('.kg-user-title').html('流程消息');
            removeobjLibadge(current.chatObj);
            $('.sz-flowbox').empty();
            flowrender();
            break;
          case 2:
            current.chatType = 2;
            groupgetobj(id);
            break;
          case 1:
            current.chatType = 1;
            friendgetobj(id);
            break;
        }
      },
      groupToSend: function (elem, e) {//消息列表里的行事件
        current.chatType = 2;
        removechatlogbox();
        var group_id = elem.data('id');
        groupgetobj(group_id);
      },
      doSend: function (elem, e) {
        sendMessage();
      },
      flowRow: function (elem, e) {
        elem.addClass('ithis');
        openview({
          title: '流程消息',
          url: elem.data('url')
        });
      },
      sysmsgRow: function (elem, e) {
        elem.addClass('ithis');
        openview({
          title: '系统消息',
          url: elem.data('url')
        });
      }
    }

  //API
  var SZIM = function () {
    console.group("SZIM v1.0.0");
    console.log("作者：恺哥");
    console.log('昵称：kaige');
    console.log('邮箱：sudukai@qq.com');
    console.log('版权：泉州市盛筑信息科技有限公司');
    console.groupEnd();
    $("body").on("click", "*[szim-event]", function (c) {
      var a = $(this), b = a.attr("szim-event");
      events[b] ? events[b].call(this, a, c) : "";
    });
  };
  //配置
  SZIM.prototype.config = function (o) {
    if (!szoa) { layer.msg('配置位置错误！'); return; }
    o = o || {};
    o = $.extend({
      szpc: (document.location.protocol || '') + '//' + szoa.client.domain + szoa.client.path,
      avatar: '/static/chat/a256.jpg',
      voice: (szoa.client.idcSrc || '/static/video/message.mp3'),
      searchKey: 'keywords',
      minTitle: '沟通',
    }, o);
    if (!window.JSON || !window.JSON.parse) return;
    cache.base = o; //存储基础配置
    init(o);
    return this;
  };

  //暴露接收消息
  SZIM.prototype.getMessage = function (d) {
    return getMessage(d), this;
  };


  //暴露
  exports('szim', new SZIM());
});

